#!/bin/bash -e

skip="$1"
clang="$2"

if [ -z "${clang}" ]; then
  clang="$(grep CLANG_EXECUTABLE build/CMakeCache.txt | sed -e 's/CLANG_EXECUTABLE:FILEPATH=//')"
fi

if [ -n "${clang}" ]; then
  if [ -x "$(dirname ${clang})/clang-format" ]; then
      clang_format="$(dirname ${clang})/clang-format"
  fi
fi

if [ ! -x "$clang_format" ]; then
  if [ $(which clang-format 2> /dev/null) ]; then
    clang_format=clang-format
  else
    echo clang-format: command not found >&2
    # TODO: fail if clang_format is missing
    exit 0
  fi
fi

# check that the required CPP files are correctly formatted.

bad=""
for file in $(find $skip/tests -name \*.cpp -o -name \*.h); do
  if diff -u $file \
     <($clang_format -style=file -sort-includes=false $file); then
    true
  else
    bad="$bad $file"
  fi
done

if [ -n "$bad" ]; then
  if [ "$UPDATE_BASELINE" == 1 ]; then
    echo "Running clang-format on the following files: $bad" >&2
    $clang_format -i -style=file -sort-includes=false $bad
  else
    echo 'The following files are not correctly formatted.' >&2
    echo 'run tools/format_cpp to fix them:' >&2
    echo "$bad" >&2
    exit 1
  fi
fi
exit 0
